package com.ydm.myapp001.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.ydm.myapp001.R;
import com.ydm.myapp001.service.MyBindService;

public class BindServiceActivity extends AppCompatActivity {
    Intent intent1;
    MyBindService service;
    ServiceConnection conn = new ServiceConnection() {
        @Override //当启动源跟Service成功连接之后将会自动调用这个方法
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            service = ((MyBindService.MyBinder)iBinder).getService();
            //得到已经绑定的service，之后就可以在Activity中调用service的方法了，如音乐播放等等
        }

        @Override //当启动源跟Service的连接意外丢失的时候会调用这个方法 -- 比如当Service崩溃了或者被强行杀死了，正常解绑不会调用这个方法
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_service);
    }

    public void doClick(View v) {
        switch(v.getId()){
            case R.id.btn_bind_service: {
                intent1 = new Intent(BindServiceActivity.this, MyBindService.class);
                bindService(intent1, conn, BIND_AUTO_CREATE);
            }
                break;
            case R.id.btn_unbind_service: {
                unbindService(conn); //服务只能解绑一次，如果多次解绑服务程序就会闪退
            }
            break;
            case R.id.btn_play_music: {
                service.play();
            }
            break;
            case R.id.btn_pause_music: {
                service.pause();
            }
            break;
            case R.id.btn_next_music: {
                service.next();
            }
            break;
            case R.id.btn_previous_music: {
                service.previous();
            }
            break;
            default:
                break;
        }
    }
}
